using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace SharePointing.Features.MetaTags
{
    /// <summary>
    /// This class was appropriated from the Codeplex Project located here: http://www.codeplex.com/SPWCMUtils
    /// We decided to take another approach to this but I wanted to leave this in the project for reference
    /// and potential re-use
    /// </summary>
    [DefaultProperty("Text"), ToolboxData("<{0}:METATagsGenerator runat=server></{0}:METATagsGenerator>")]
    public class METATagsGenerator : WebControl
    {
        string metaGroupName = "META";

        public string METAGroupName
        {
            get { return metaGroupName; }
            set { metaGroupName = value; }
        }

        /// <summary> 
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {

            //get the placeholder that holds the meta tag content
            SPContext spc = SPContext.Current;
            PublishingPage page = PublishingPage.GetPublishingPage(spc.ListItem);
            if (page != null)
            {
                SPContentType contentType = page.ContentType;
                foreach (SPField f in contentType.Fields)
                {
                    if (f.Group.Equals(METAGroupName))
                    {
                        if (page.ListItem[f.InternalName] != null)
                        {
                            output.Write("<META");
                            output.WriteAttribute("name", f.Title);
                            output.WriteAttribute("content", page.ListItem[f.InternalName].ToString());
                            output.Write(">");
                        }
                    }
                }
            }
        }
    }
}